#include "Player.h"

static Player* _Player = nullptr;
static std::mutex PlayerCreateLock;

Player::Player()
{
	_PlayerMsgQueue.MsgQueue.clear();
	_Player = this;
	_PlayerSocket = SocketClient::GetInstance();
	std::thread SendMsgThread = std::thread(&Player::PlayerSendMsgThread, this);
	SendMsgThread.detach();
}

Player::~Player()
{

}

Player* Player::GetInstance()
{
	if (!_Player)
	{
		ThreadLocker Locker(PlayerCreateLock);
		if (!_Player)
		{
			_Player = new Player();
		}
	}
	return _Player;
}

void Player::PlayerSendMsgThread()
{
	while (true)
	{
		if (!_PlayerMsgQueue.MsgQueue.empty())
		{
			//Lock
			ThreadLocker Locker(PlayerMessageLock);
			sSocket->sendMessage(_PlayerMsgQueue.MsgQueue.at(0).c_str(), sizeof(_PlayerMsgQueue.MsgQueue.at(0).c_str()));
			std::vector<std::string>::iterator itr = _PlayerMsgQueue.MsgQueue.begin();
			_PlayerMsgQueue.MsgQueue.erase(itr);
		}
	}
}

void Player::PlayerAddMsgThread(std::string msg)
{
	while (1)
	{
		ThreadLocker Locker(PlayerMessageLock);
		_PlayerMsgQueue.MsgQueue.push_back(msg);
		break;
	}
}

void Player::AddMsgToList(std::string msg)
{
	std::thread th(&Player::PlayerAddMsgThread, this, msg);
	th.detach();
}